// 短信登录组件
// src/pages/login/widgets/message/index.tsx
import styles from "@styles/login.module.scss";
import classNames from "classnames";
import {z} from "zod";
import {SubmitHandler, useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {useEffect} from "react";
import {Toast} from "antd-mobile";
import {useLoginByMsgCodeMutation, useSendMsgCodeMutation} from "@store/apiSlice/authApiSlice";
import useCountDown from "@hooks/useCountDown";
import {useTypedDispatch} from "@store/index";
import {useNavigate} from "react-router-dom";
import {saveAuth} from "@store/slices/authSlice";

// 表单状态类型
export interface FormState {
    mobile: string;
    code: string;
    isAgree: boolean;
}
// 表单验证规则
const schema = z.object({
    mobile: z
        .string({
            invalid_type_error: "手机号参数类型错误",
            required_error: "请检查手机号字段名称是否正确",
        })
        .min(1, "请输入手机号")
        .regex(/^1[3-9]\d{9}$/, "手机号格式错误"),
    code: z
        .string({
            invalid_type_error: "验证码参数类型错误",
            required_error: "请检查验证码字段名称是否正确",
        })
        .length(6, "验证码格式错误"),
    isAgree: z.literal(true, {
        errorMap: () => ({ message: "请勾选协议" }),
    }),
});
export default function Message() {
    // 表单验证对象
    const {
        register,
        formState: { errors, isValid },
        handleSubmit,
        getFieldState,
        getValues
    } = useForm<FormState>({
        // 在用户输入的过程中实时触发验证
        mode: "onChange",
        // 状态默认值
        defaultValues: { mobile: "", code: "" },
        // 设置表单验证器
        resolver: zodResolver(schema),
    });
    // 检测用户是否勾选同意协议
    useEffect(() => {
        if (typeof errors.isAgree !== "undefined") {
            Toast.show({ content: "请勾选同意协议" });
        }
    }, [errors.isAgree]);
    // 表单提交
    const onSubmit: SubmitHandler<FormState> = ({ mobile, code }) => {
        loginByMsgCode({ mobile, code })
            .unwrap()
            .then((response) => {
                // 登录失败
                if (
                    typeof response.success !== "undefined" &&
                    response.success === false
                ) {
                    return Toast.show({ content: response.message });
                }
                // 登录成功, 保存用户登录凭据
                dispatch(saveAuth(response.data));
                // 消息提示
                Toast.show({
                    content: "登录成功",
                    afterClose: () => {
                        // 跳转到个人中心页面
                        navigate("/personal");
                    },
                });
            });

    };
    // 表单验证对象

    //用于发送手机验证码
    const [sendMsgCodeRequest] = useSendMsgCodeMutation()
    // 用于倒计时
    const { seconds, start, isActive } = useCountDown();
    // 发送手机验证码
    const sendMsgCodeEventHandler = () => {
        // 如果正在倒计时, 阻止代码继续运行
        if (isActive) return;
        // 获取手机号字段状态
        const { isTouched, error } = getFieldState("mobile");
        // 判断用户是否输入了手机号
        if (isTouched && typeof error === "undefined") {
            // 如果用户输入了正确格式的手机号
            // 执行发送手机验证码的请求
            sendMsgCodeRequest({ mobile: getValues("mobile"), type: "login" })
                .unwrap()
                .then((response) => {
                    // 发送验证码失败, 比如参数类型错误、用户不存在、验证码已存在
                    if (
                        typeof response.success !== "undefined" &&
                        response.success === false
                    ) {
                        // 用户提示
                        Toast.show({ content: response.message });
                    } else {
                        // 开启倒计时
                        start(60);
                        // 用户提示
                        Toast.show({ content: "手机验证码发送成功" });
                    }
                })
                .catch(() => {
                    // 发送验证码失败, 比如没有网络
                    Toast.show({ content: "手机验证码发送失败" });
                });
        } else {
            // 用户没有输入手机号或没有输入正确格式的手机号
            Toast.show({ content: "请输入正确格式的手机号" });
        }
    };
    // 用于短信登录
    const [loginByMsgCode] = useLoginByMsgCodeMutation();
    // 获取 dispatch 方法
    const dispatch = useTypedDispatch();
    // 获取路由信息对象
    const navigate = useNavigate();
    return (
    <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
      <div className={styles.formItem}>
        <input type="text" placeholder="请输入手机号"  className={styles.text}     {...register("mobile")} />
          {errors.mobile && <p className={styles.msg}>{errors.mobile.message}</p>}
      </div>
      <div className={styles.formItem}>
        <input
          type="text"
          placeholder="请输入短信验证码"
          className={styles.text}
          {...register("code")}
        />
        <div className={styles.right} onClick={sendMsgCodeEventHandler}>
          <div  className={styles.sendMsgCode}>
              {isActive ? `${seconds}秒后再次发送` : "发送手机验证码"}
          </div>
        </div>
          {errors.code && <p className={styles.msg}>{errors.code.message}</p>}
      </div>
      <div className={styles.formItem}>
        <label className={styles.agree}>
          <input type="checkbox" {...register("isAgree")} />
          <span>
            我已同意<a href="#"> 用户协议 </a>及<a href="#"> 隐私条款</a>
          </span>
        </label>
      </div>
        <button className={classNames(styles.submit, { [styles.disabled]: !isValid })}>登录</button>
    </form>
  );
}
